package com.von.nhcf.mvc.config;

import com.von.nhcf.entity.Admin;
import com.von.nhcf.entity.Role;
import com.von.nhcf.service.AdminService;
import com.von.nhcf.service.AuthService;
import com.von.nhcf.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Admin的SpringSecurity UserDetails
 * @author von
 */
@Component
public class AdminUserDetails implements UserDetailsService {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 根据账号查询admin
        Admin admin = adminService.getAdminByAccount(account);

        Integer adminId = admin.getId();

        List<Role> roleList = roleService.getAssignedRole(adminId);

        List<String> authNameList = authService.getAssignedAuthNameByAdminId(adminId);

        // 创建集合对象用来存储 GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 封装权限名集合
        for (Role role : roleList) {
            // 添加权限的前缀
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        // 封装角色名集合
        for (String authName : authNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }
        // 封装admin和authorities
        AdminToSecurityUser user = new AdminToSecurityUser(admin, authorities);

        return user;
    }
}
